<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Auth extends Base
{
    // 权限列表
    public function index()
    {
        $title = "权限管理";

        // 权限的所有数据
        $data = \app\admin\model\Auth::select();

        $getTree = getTree($data);

        return view("/auth/index",[
            'title' => $title,
            'getTree' => $getTree
        ]);
    }

    // 新增权限管理
    public function add()
    {
        $title = "添加权限";

        $data = \app\admin\model\Auth::select();

        return view("/auth/add",[
            'title' => $title,
            'data' => $data
        ]);
    }

    // 添加权限管理
    public function insert(Request $request)
    {
        $data = $request->param();
        // 顶级分类 可以不需要有控制器和方法
        if($data['pid'] == 0){
            if(empty($data['auth_name'])){
                $this->error("权限名称不允许为空哦",'admin/Auth/add');
                die;
            }
        }else{
            $rule = [
                'auth_name|权限名称' => 'require|token',
                'pid|上级分类' => 'require',
                'auth_c|控制器' => 'require',
                'auth_a|控制器方法' => 'require',
                'is_nav|是否显示' => 'require',
            ];

            $validate = new \think\Validate($rule);
            if(!$validate->check($data))
            {
                $error = $validate->getError();
                $this->error($error);
            }
        }
        \app\admin\model\Auth::create($data,true);

        $this->success("添加成功","admin/Auth/add");
    }

    // 修改权限管理
    public function edit(int $id)
    {

        $title = "修改权限";

        if(empty($id)){
            $this->error("参数错误",'admin/auth/edit');
            die;
        }
        // 单独的一条数据
        $data = \app\admin\model\Auth::find($id);

        // 分类数据
        $dataTree = \app\admin\model\Auth::select();

        return view("/auth/exit",[
            'title' => $title,
            'data' => $data,
            'dataTree' => $dataTree
        ]);
    }

    // 更新权限管理
    public function update(Request $request)
    {
        $data = $request->param();

        // 进行判断
        $rule = [
            'auth_name|权限名称' => "require|token",
            'pid|上级id' => 'require',
            'is_nav|菜单选项' => 'require'
        ];

        $validate = new \think\Validate($rule);

        if(!$validate->check($data))
        {
            $error = $validate->getError();
            $this->error($error);
        }

        # 更新数据库
        \app\admin\model\Auth::update($data,['id'=>$data['id']],true);

        $this->success("修改成功","admin/Auth/index");
    }

    // 删除权限
    public function delete(int $id)
    {
        if(empty($id))
        {
            $this->error("参数错误","admin/Auth/index");
            die;
        }

        \app\admin\model\Auth::destroy($id);

        $this->success("删除成功","admin/Auth/index");

    }
}
